const axios = require('axios').default;

const instance = axios.create({
  baseURL: 'https://api.weixin.qq.com/cgi-bin',
  headers: {
    'Content-Type': 'application/json',
  },
  method: 'POST',
  timeout: 1000 * 60 * 5, // 5分钟
});

/**
 * 响应拦截器
 */
instance.interceptors.response.use(
  function (res) {
    const { errcode, errmsg } = res.data;
    if (errcode) {
      throw new Error(`微信接口服务异常, ${errcode}, ${errmsg}`);
    }
    return res.data;
  },
  function (error) {
    throw error;
  }
);

const getAccessToken = async () => {
  const { access_token: accessToken } = await instance({
    method: 'GET',
    url: 'token',
    params: {
      grant_type: 'client_credential',
      appid: process.env.APPID,
      secret: process.env.APPSECRET,
    },
  });
  global.ACCESS_TOKEN = accessToken;
  return accessToken;
};

module.exports = { getAccessToken };
